﻿using MediatR;
using Medical.Api.Read.Application.Command.DepartmentManagement.Recycling;
using Medical.Domain.DepartmentInfo;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

namespace Medical.Api.Read.Application.Handler.DepartmentManagement.Recycling
{
    /// <summary>
    /// 回收申请表查询处理器
    /// </summary>
    public class GetRecyclingCommandHandler : IRequestHandler<GetRecyclingCommands, ApiResult<ApiPageIng<RecyclingTable>>>
    {
        private readonly ILogger<GetRecyclingCommandHandler> logger;
        private readonly IBaseRepository<RecyclingTable> recyclingRep;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志记录器</param>
        /// <param name="recyclingRep">回收申请表仓储接口</param>
        public GetRecyclingCommandHandler(ILogger<GetRecyclingCommandHandler> logger, IBaseRepository<RecyclingTable> recyclingRep)
        {
            this.logger = logger;
            this.recyclingRep = recyclingRep;
        }

        /// <summary>
        /// 处理回收申请表查询请求
        /// </summary>
        /// <param name="request">查询请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>回收申请表分页数据</returns>
        public async Task<ApiResult<ApiPageIng<RecyclingTable>>> Handle(GetRecyclingCommands request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation($"开始查询回收申请表列表，申请时间：{request.ApplicationTime}");
                
                // 获取未删除的所有回收申请记录
                var query = recyclingRep.GetAll().Where(x => !x.IsDeleted);
                
                // 如果提供了申请时间，则按申请时间筛选
                // 查询当天的记录（从当天0点到23:59:59）
                if (request.ApplicationTime != DateTime.MinValue)
                {
                    DateTime startDate = request.ApplicationTime.Date;
                    DateTime endDate = startDate.AddDays(1).AddSeconds(-1);
                    
                    query = query.Where(x => x.ApplicationTime >= startDate && x.ApplicationTime <= endDate);
                    
                    logger.LogInformation($"按申请时间筛选：{startDate} 至 {endDate}");
                }
                
                // 如果提供了回收状态，则按状态筛选
                if (request.RecyclingStatus != 0)
                {
                    query = query.Where(x => x.RecyclingStatus == request.RecyclingStatus);
                }

                // 获取总记录数
                int totalCount = await query.CountAsync(cancellationToken);
                
                // 按申请时间降序排序并分页
                var recyclingList = await query
                    .OrderByDescending(x => x.ApplicationTime)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);
                
                // 构建分页结果
                var pageResult = new ApiPageIng<RecyclingTable>
                {
                    PageData = recyclingList,
                    TotalCount = totalCount,
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize
                };
                
                logger.LogInformation($"回收申请表列表查询成功，返回 {recyclingList.Count} 条记录，总记录数：{totalCount}");

                return new ApiResult<ApiPageIng<RecyclingTable>>
                {
                    Code = ApiEnums.Success,
                    Data = pageResult,
                    Msg = "回收申请表列表显示成功!"
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"查询回收申请表列表时发生异常：{ex.Message}");
                
                return new ApiResult<ApiPageIng<RecyclingTable>>
                {
                    Code = ApiEnums.Error,
                    Data = new ApiPageIng<RecyclingTable>(),
                    Msg = $"查询回收申请表列表失败：{ex.Message}"
                };
            }
        }
    }
}
